import Request from "./request";
import apiList from "./api";

function getApiObj(url) {
    let apiArray = url.split(".");
    // 根据Url获取相应的接口地址，以及相应的地址访问配置
    let api = apiList;
    apiArray.forEach(v => {
        api = api[v] || {};
    });
    return JSON.parse(JSON.stringify(api));
}

/**
 * 
 * @param {*} url 
 * @param {*} data 
 * @param {*} params 
 * @returns 
 * 
 * 关于bind: 
 * 使用api.bind({
 * url: '' //传入具体地址的话使用具体地址，
 * endUrl: ''//这个是尾部拼接地址
 * 
 * })
 * 
 */
export default function api(url, data = {}, params = {}) {
    let api = getApiObj(url);
    if(this&&this.url){
        api.url = this.url;
    } else if((this&&this.endUrl)||(this.endUrl==0)){
        api.url = api.url+'/'+this.endUrl;
    }
    
    const method = (api.method || "").toLowerCase();

    let requestHeaders = {};
	if(api && api.requestHeaders) {
		requestHeaders = api.requestHeaders;
	} else {
        if(new RegExp("post").test(method)){
            requestHeaders = {
                headers: {
					'Content-Type': "application/json"
				}
            };
        } else {
            requestHeaders = {};
        }
	}

    if(new RegExp("post").test(method)){
        return Request({
            url: api.url,
            data: JSON.stringify(data || {}),
            params: params,
            method: api.method,
            ...requestHeaders
        })
    } else {
        return Request({
            url: api.url,
            params: data,
            method: api.method,
            ...requestHeaders
        })
    }
}